//
//  RegisterViewController.m
//  DBAChain
//
//  Created by Mxionlly on 2018/9/6.
//  Copyright © 2018年 Evan. All rights reserved.
//

#import "RegisterViewController.h"
#import "taskUserManagerService.h"
#import "GeneralTool.h"

@interface RegisterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UITextField *passWordField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UITextField *invitationField;

@property (nonatomic, strong) NSTimer           *timer;
@property (nonatomic, assign) NSInteger         number;

///短信收到的验证码
@property (nonatomic, strong) NSString*         verifyCode;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initUI];
}

-(void)viewWillAppear:(BOOL)animated{
    self.hidesBottomBarWhenPushed = NO;
    if (self.tabBarController.tabBar.hidden == YES) {
        self.tabBarController.tabBar.hidden = NO;
    }
    if (self.navigationController.navigationBar.hidden == NO) {
        self.navigationController.navigationBar.hidden = YES;
    }
}

-(void)initUI
{
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSliderAction)]];
    self.number = 60;
    self.registerButton.layer.masksToBounds = YES;
    self.registerButton.layer.borderWidth = 1.0f;
    self.registerButton.layer.borderColor = [UIColor clearColor].CGColor;
    self.registerButton.layer.cornerRadius = 24.0f;
    
    [self.phoneField setValue:[UIColor colorWithWhite:1 alpha:0.8] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passWordField setValue:[UIColor colorWithWhite:1 alpha:0.8] forKeyPath:@"_placeholderLabel.textColor"];
    [self.codeField setValue:[UIColor colorWithWhite:1 alpha:0.8] forKeyPath:@"_placeholderLabel.textColor"];
    [self.invitationField setValue:[UIColor colorWithWhite:1 alpha:0.8] forKeyPath:@"_placeholderLabel.textColor"];
    
    [self initCodeView:@"发送验证码"];
}

-(void)initCodeView:(NSString *)title
{
    NSMutableAttributedString* tncString = [[NSMutableAttributedString alloc] initWithString:title];
    [tncString addAttribute:NSUnderlineStyleAttributeName
                      value:@(NSUnderlineStyleSingle)
                      range:(NSRange){0,[tncString length]}];
    [tncString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor]  range:NSMakeRange(0,[tncString length])];
    [tncString addAttribute:NSUnderlineColorAttributeName value:[UIColor whiteColor] range:(NSRange){0,[tncString length]}];
    [self.codeButton setAttributedTitle:tncString forState:UIControlStateNormal];
}

- (IBAction)getCodeAction:(id)sender {
    if (![Check isMobileNumber:self.phoneField.text]) {
        [DKProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }else{
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setField:self.phoneField.text value:@"phone"];
        [taskUserManagerService getVerifyCode:dict success:^(dataGetVerifyCode *response, BOOL success) {
            if (success) {
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updataAction) userInfo:nil repeats:YES];
                self.codeButton.userInteractionEnabled = NO;
                self.verifyCode = response.data;
                return ;
            }
            [DKProgressHUD showErrorWithStatus:@"发送失败"];
        } failture:^(NSError *error, NSString *strDescription) {
            NSString *strErr = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            [DKProgressHUD showErrorWithStatus:strErr];
        }];
    }
}

- (void)updataAction {
    self.number--;
    [self initCodeView:[NSString stringWithFormat:@"%lds",(long)self.number]];
    if (self.number <= 0) {
        [self closeTimer];
    }
}

- (void)closeTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
        self.number = 60;
        self.codeButton.userInteractionEnabled = YES;
        [self initCodeView:@"发送验证码"];
    }
}

- (IBAction)loginAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)registerAction:(id)sender {
    
    if (![Check isMobileNumber:self.phoneField.text]) {
        [DKProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    if (![Check checkLenght:self.codeField.text]) {
        [DKProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    if (![Check checkLenght:self.passWordField.text] || self.passWordField.text.length < 6) {
        [DKProgressHUD showErrorWithStatus:@"请设置6位及以上密码"];
        return;
    }
    if (self.codeField.text != self.verifyCode) {
        [DKProgressHUD showErrorWithStatus:@"您输入的验证码有误"];
        return;
    }
    if (![Check checkLenght:self.invitationField.text]) {
        [DKProgressHUD showErrorWithStatus:@"请输入邀请码"];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setField:self.phoneField.text value:@"phone"];
    [dict setField:self.passWordField.text value:@"password"];
    [dict setField:self.codeField.text value:@"verifyCode"];
    [dict setField:self.invitationField.text value:@"inviteCode"];//Y6X1N1
    [DKProgressHUD showLoading];
    [taskUserManagerService getRegister:dict success:^(BaseModel *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            [DKProgressHUD showSuccessWithStatus:@"注册成功"];
            [NSThread sleepForTimeInterval:2];
            [self goBack:nil];
        }else{
            [DKProgressHUD showErrorWithStatus:response.statusDesc];
            return;
        }
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
        return;
    }];
}

-(void)tapSliderAction
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
